//
//  ZJBannerView.m
//  YueLoveBaby
//
//  Created by 张敬 on 2018/5/15.
//  Copyright © 2018年 张敬. All rights reserved.
//

#import "TJBannerView.h"
#import "TJBannerCell.h"
#import "TJBannerHeader.h"
#import "JhPageControl.h"

#import <SDWebImage/UIImageView+WebCache.h>

static NSTimeInterval const bannerTimeInterval_ = 2.0f;
static float const bannerViewHeight_ = 140;
static NSInteger bannerPageIndex_ = 0;

@interface TJBannerView()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *collectionArray;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) JhPageControl *pageControl;


@end

@implementation TJBannerView
#pragma mark - lifeCycle
- (instancetype)init
{
    self = [super init];
    if (self) {
        _imageArray = @[];
        _currentIndex = 0;

        [self addBannerSubView];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.collectionView.frame = self.bounds;
    if (CGRectEqualToRect(self.bannerPageControlFrame, CGRectZero)) {

        float w = self.frame.size.width;
        float h = 26.0;
        float x = 0;
        float y = self.frame.size.height - h;
        self.pageControl.frame = CGRectMake(x, y, w, h);
    }
    self.currentIndex = 1;
    self.pageControl.numberOfPages = self.collectionArray.count-2;
    self.pageControl.currentPage = _currentIndex -1;
    _collectionView.contentOffset = CGPointMake(self.bounds.size.width, 0);
}

#pragma mark - timer methods
- (void)bannerTimerSuspended
{
    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)bannerTimerContinued
{
    [_timer setFireDate:[NSDate date]];
}

- (void)addBannerTimer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:bannerTimeInterval_ target:self selector:@selector(didBannerRunLoop) userInfo:nil repeats:YES];
    }
}

- (void)destroyBannerTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark - private methods
//获取数据源
- (NSMutableArray *)getDataScouces:(NSArray *)dataScoures
{
    NSMutableArray *aimsArray = [NSMutableArray array];
    if (dataScoures && [dataScoures isKindOfClass:[NSArray class]]) {
        aimsArray = [NSMutableArray arrayWithArray:dataScoures];
        id fristObjection = [dataScoures firstObject];
        id lastObjection = [dataScoures lastObject];
        
        [aimsArray insertObject:lastObjection atIndex:0];
        [aimsArray addObject:fristObjection];
    }
    return aimsArray;
}

//加载子控件
- (void)addBannerSubView
{
    [self addSubview:self.collectionView];
    [self addSubview:self.pageControl];
}

//轮播图向左滑
- (void)bannerMoveLeftWithIndex:(NSInteger)index
{
    if (index == _collectionArray.count-1) {
        _currentIndex = 1;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }else{
        _currentIndex = index;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
    bannerPageIndex_ = _currentIndex -1;
    _pageControl.currentPage = bannerPageIndex_;
}

//轮播图向右滑
- (void)bannerMoveRightWithIndex:(NSInteger)index
{
    if (index == 0) {
        _currentIndex = self.collectionArray.count-2;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
         [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }else{
        _currentIndex = index;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
    bannerPageIndex_ = _currentIndex -1;
    _pageControl.currentPage = bannerPageIndex_;
}

#pragma mark - SEL
- (void)didBannerRunLoop
{
    NSInteger index = ++self.currentIndex;
    [self bannerMoveLeftWithIndex:index];
}

#pragma mark - UICollectionView.dataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectionArray.count ?_collectionArray.count :0;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TJBannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[TJBannerCell cellReuseIndentifier] forIndexPath:indexPath];
    
    NSString *imageName = _collectionArray[indexPath.item];
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:imageName]];
    imageView.frame = self.bounds;
    [cell.contentView addSubview:imageView];
    
    return cell;
}

#pragma mark - UICollectionView.delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger myIndex = indexPath.item;
    if (self.bannerBlock) {
        self.bannerBlock(myIndex);
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(banber:clickedBannerIndex:)]) {
        [self.delegate banber:self clickedBannerIndex:myIndex];
    }
}

#pragma mark - UIScrollView.delegate
//拖拽开始时关闭定时器，定时器一旦关闭，就不能再重新开启
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self destroyBannerTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addBannerTimer];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/self.bounds.size.width;
    if (index <= bannerPageIndex_) {
        [self bannerMoveRightWithIndex:index];
    }
    else
    {
        [self bannerMoveLeftWithIndex:index];
    }
}

#pragma mark - getter Methods
- (void)setImageArray:(NSArray *)imageArray
{
    if (_imageArray != imageArray) {
        _imageArray = imageArray;
    }
    
    if (_imageArray.count >0) {
        _collectionArray = [self getDataScouces:imageArray];
        [self addBannerTimer];
    }
    
    if (_imageArray && _imageArray.count == 1) {
        _collectionView.scrollEnabled = NO;

    }else{
        _collectionView.scrollEnabled = YES;
    }
    
    self.pageControl.numberOfPages = self.imageArray.count;
    [_collectionView reloadData];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = KWhiteColor;
        [_collectionView registerClass:[TJBannerCell class] forCellWithReuseIdentifier:[TJBannerCell cellReuseIndentifier]];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(bannerScreenWidth, bannerViewHeight_);
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _layout.minimumInteritemSpacing = 0.0f;
        _layout.minimumLineSpacing = 0.0f;
    }
    return _layout;
}


- (JhPageControl *)pageControl{
    if (!_pageControl) {
        
        JhPageControl *pageControl = [[JhPageControl alloc] init];
        pageControl.currentPage = 0;
        pageControl.otherColor = UIColorFromRGB(0xE6E6E6);
        pageControl.currentColor = mMainColor;
        pageControl.PageControlContentMode = JhPageControlContentModeCenter;
        pageControl.controlSpacing = 3;
        pageControl.marginSpacing = 0;
        pageControl.PageControlStyle = JhPageControlStyelRectangle;
        _pageControl = pageControl;
        
       [self addSubview:self.pageControl];
        
    }
    return _pageControl;
}


#pragma mark - setter Methods
- (void)dealloc
{
    [self destroyBannerTimer];
}

@end
